import usb

class UsbDevice:
    def __init__(self, idVendor, idProduct):
        busses = usb.busses()
        for bus in busses:
            devices = bus.devices
            for device in devices:
                #print hex(device.idVendor), hex(device.idProduct)
                if (device.idVendor, device.idProduct) == (idVendor, idProduct):
                    self.device = device
                    self.configuration = self.device.configurations[0]
                    self.interface = self.configuration.interfaces[0][0]
                    self.endpoints = []
                    self.pipes = []
                    for endpoint in self.interface.endpoints:
                        self.endpoints.append(endpoint)
                        self.pipes.append(endpoint.address)
                        return
        raise RuntimeError, 'Device not found'

    def open(self):
        if hasattr(self, 'handle'):
            raise RuntimeError, 'Device already opened'
        self.handle = self.device.open()
        self.handle.setConfiguration(self.configuration)
        self.handle.claimInterface(self.interface)
        self.handle.setAltInterface(self.interface)
            
    def close(self):
        if hasattr(self, 'handle'):
            self.handle.releaseInterface()
            del self.handle
        else:
            raise RuntimeError, 'Device not opened'
  
    def bulkWrite(self, pipeno, buffer, timeout=100):
        if hasattr(self, 'handle'):
            self.handle.bulkWrite(self.pipes[pipeno], buffer, timeout)
        else:
            raise RuntimeError, 'Device not opened'

    def bulkRead(self, pipeno, size, timeout=100):
        if hasattr(self, 'handle'):
            data = self.handle.bulkRead(self.pipes[pipeno], size, timeout)
            return map(lambda x: 0xFF & x, data)
        else:
            raise RuntimeError, 'Device not opened'
 
if __name__=='__main__':
    device = UsbDevice(0x0403,0x6001) # EZ-USB FX2
    device.open()
    #print device.pipes
    device.bulkWrite(0, [0])
    print device.bulkRead(2, 12, 1000)
    device.close()
